<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/27
 * Time: 15:53
 */

namespace app\index\server;


use app\index\model\Coupon as CouponModel;
use app\index\model\User as UserModel;
use app\lib\exception\DatabaseException;
use think\Exception;
use think\Db;
class CouponServer extends BaseServer
{
    public function getList($params = [])
    {
        $params = $this->prep_param($params);
        try {
            // 总条数
            $count = UserModel::count();
            $list = UserModel::where('is_vip' ,'=',3)
                ->order($params['sort'], $params['order'])
                ->limit($params['offset'], $params['limit'])
                ->select();
        } catch (Exception $e) {
            // 有些问题 应该抛出错误异常
           throw new DatabaseException([
               'msg' => $e->getMessage()
           ]);
        }
        return bootstrap_table_return($count, $list);
    }

    public function addOrUpdate($params = [])
    {      
        // var_dump($params['uid']);die;
        try {
            $result = CouponModel::insert([
                'uid' => $params['uid'],
                'code' => 1515155144,
                'price' => $params['price']
            ]);
            if(!$result){
                return setMsg(0, '新增优惠券失败');
            }
        }catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '新增优惠券成功');
    }


    public function detail($id)
    {
        try {
            $result = UserModel::where('id', '=', $id)
                ->find();
            if(!$result) {
                return setMsg(0, '未找到此信息');
            }
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, 'OK', $result);
    }


    public function changeStatus($id)
    {
        try {
            $info = UserModel::where('id', $id)
                ->find();
            $info->status = abs(($info->status) - 1);
            $result = $info->save();
            if(!$result) {
                return setMsg(0, '修改此分类状态失败');
            }
        }catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '修改此分类 状态成功');
    }


}